'use strict';
/*获取服务器域名*/
function getServer(server){
    var host = document.domain;
    var hostArr = host.split(".");
    var domain = "//"+server+".mbalib.com";
    if(hostArr[1] == 'dev' || hostArr[1] == 'test' || hostArr[1] == 'test2' ) {
        domain = "//"+server+"."+hostArr[1]+".mbalib.com";
        if(server=='img' && (hostArr[1] == 'test2' || hostArr[1] == 'test')){
            domain = "//static."+hostArr[1]+".mbalib.com";
        }
    }
    return domain;
}

var getFoldersUrl = getServer('passport')+'/favoriteapi/GetFolders';
var collectUrl = getServer('passport')+'/favoriteapi/Collect';
var unCollectUrl = getServer('passport')+'/favoriteapi/Uncollect';
var updateFolderUrl =  getServer('passport')+'/favoriteapi/updateFolder';
var hasCollectUrl =  getServer('passport')+'/favoriteapi/hasCollect';

var token = wfGetCookie('wikidbAccessToken');
var login_token =  wfGetCookie('wikidbLoginToken');
var request_time = 0;

function closeDialog(){
    $("#bg").hide();
    $(".common-Dialog").addClass("hid");
    document.documentElement.style.overflow = "visible";
}
function freshUserInfo(result,fn_request,fn_success,fn_request_params) {
    var login_token =  wfGetCookie('wikidbLoginToken');
    //用户信息无效
    if(result && result.errorno==10001){
        if(!token && !login_token){
            unLogin();
            return;
        }
        //重新发起请求
        $.ajax({
            url:getServer('passport')+'/api2/accesstoken',
            data: {login_token : login_token},
            dataType : 'json',
            async: false,
        }).done(function(result){
            token = result.access_token;
            if(typeof wfSetCookie === 'function' ){
                wfSetCookie("wikidbAccessToken",token,60,".mbalib.com");
            }
            fn_request(fn_request_params);
        }).fail(function(){});
    }else{
        fn_success(result);
    }
}

function unLogin(){
    window.location.href = getServer('passport')+'/login'+'?continue='+encodeURIComponent(window.location.href);
    return false;
}

var favoriteObj = {
    id:'',
    type:'',
    triggerBtn:'',
    collectCount:0,
    collectEvent:function () {},
    uncollectEvent:function () {},
    init:function (id,type,triggerBtn,collectEvent,uncollectEvent) {
        this.id=id;
        this.type=type;
        this.triggerBtn=triggerBtn;
        this.collectEvent=collectEvent;
        this.uncollectEvent=uncollectEvent;
        this.hascollect();
        this.addpop();
        this.bindEvent();
    },
    clearCellectionInfo:function () {
        $("#favName").val('');
        $("#favName").next().html(20);
        $("#collectEdit  #publicIcon").click();
        $("#saveCollection").addClass("btnDisable");
    },
    //判断是否有收藏过
    hascollect:function () {
        request_time++;
        if(request_time>3) return;

        var _this = this;
        var id = _this.id;
        var type = _this.type;
        var url = hasCollectUrl;
        // url +="?access_token="+token+"&key="+id+"&type="+type;
        var data = {access_token:token,key:id,type:type};
        if(!token && !login_token) return false;
        crossDomainAjax_post(url,onBack,data);
        function onBack(result) {
            var fn_success = function(result){
                request_time = 1;
                if (result.state=='success' && result.has_collect=='1'){
                    _this.collectEvent();
                }else{
                    _this.uncollectEvent();
                }
            }
            freshUserInfo(result,favoriteObj.hascollect.bind(_this),fn_success);
        }
    },
    //添加弹窗
    addpop:function () {
       var html='<div class="common-Dialog hid" id="collectionListBox" style="margin-top:-250px;">'+
            '<a class="closeIcon" href="javascript:void(0)"  onclick="closeDialog()" ><i></i></a>'+
            '<h4 class="title">添加收藏</h4>'+
            '<div class="body" style="margin:0">'+
            '<div class="dialog-table" style="margin:0 0 50px">'+
            '<ul class="tbody"  id="collectionList" style="height: 242px;margin:0"></ul>' +
            '</div></div>'+
            '<div class="bottom" style="width:auto">'+
            '<a style="margin:0 auto;width:180px;float: none" id="createBtn" href="javascript:void(0)"  class="cbtn-m btnlook1">新建收藏夹</a>'+
            '</div></div>'+
            '<div class="common-Dialog hid" id="collectEdit" style="margin-top:-200px">'+
            '<a class="closeIcon cancelDialog" href="javascript:void(0)" ><i></i></a>'+
            '<h4 class="title">编辑收藏夹</h4>'+
            '<div class="body" style="height: 150px;">'+
            '<div class="dialog-input">'+
            '<input type="text" autocomplete="off" placeholder="收藏夹标题" id="favName">'+
            '<span>20</span>'+
            '</div>'+
            '<input type="radio" id="public" checked="checked" name="favType" value="1" style="display: none" />'+
            '<input type="radio" id="private" name="favType" value="0" style="display: none" />'+
            '<div class="btnRadio-wr clearfix">'+
            '<label for="public">'+
            '<i class="btnRadio check" id="publicIcon"><span class="rfg"></span></i>'+
            '<p class="label">公开&ensp;<span class="fz-grey">（该收藏夹未来有关注者后，将无法设为私密）</span></p>'+
            '</label></div>'+
            '<div class="btnRadio-wr clearfix">'+
            '<label for="private">'+
            '<i class="btnRadio" id="privateIcon"><span class="rfg"></span></i>'+
            '<p class="label">私密&ensp;<span class="fz-grey">（仅自己可见）</span></p>'+
            '</label></div></div>'+
            '<div class="bottom">'+
            '<div class="bottomBtn">'+
            '<a href="javascript:void(0)" id="saveCollection" class="cbtn-m btnlook1">确定</a>'+
            '<a href="javascript:void(0)" class="cbtn-m btnlook5 cancelDialog">取消</a>'+
            '</div></div></div>';
        $("body").append(html);
    },
    //新建收藏夹
    saveCollectionInfo:function(){
        var _this = this;
        var name = $("#favName").val();
        var open = $("input[name='favType']:checked").val();

        if(!name || name ==''){
            // alert('请输入收藏夹标题');
            return;
        }
        var url = updateFolderUrl;
        url +="?access_token="+token+"&name="+name+"&open="+open;
        var data = {access_token:token,name:name,open:open};
        crossDomainAjax_post(url,onBack,data);
        function onBack(result) {
            var fn_success = function(result) {
                request_time = 1;
                if (result.state == 'success') {
                    $('#collectEdit').addClass('hid');
                    $("#collectionListBox").removeClass("hid");
                    _this.getList();
                }
            }
            freshUserInfo(result,favoriteObj.batchCollect,fn_success);
        }
    },
    //收藏和取消收藏
    batchCollect:function(method,btnSelf) {
        var _this = this;
        var url;
        if (method=='add'){
            url = collectUrl;
        }else{
            url = unCollectUrl;
        }
        var fav_id = $(btnSelf).attr('data-id');
        // url +="?access_token="+token+"&key="+_this.id+"&type="+_this.type+"&fav_id="+fav_id;
        var data = {access_token:token,key:_this.id,type:_this.type,fav_id:fav_id};
        crossDomainAjax_post(url,onBack,data);
        function onBack(result) {
            var fn_success = function(result) {
                request_time = 1;
                if(result.state=='success') {
                    if (method == 'add') {
                        var count = $(btnSelf).parents('.item-lr').find('.fc-grey').attr('data-count');
                        count = parseInt(count) + 1;
                        $(btnSelf).addClass('btnlook3').removeClass('btnlook2');
                        $(btnSelf).parents('.item-lr').find('.fc-grey').attr('data-count', count);
                        $(btnSelf).parents('.item-lr').find('.fc-grey').html(count + '&ensp;条内容');
                        $(btnSelf).html('已收藏');
                        _this.collectCount++;
                        _this.collectEvent();
                    } else if (method == 'delete') {
                        var count = $(btnSelf).parents('.item-lr').find('.fc-grey').attr('data-count');
                        count = parseInt(count) - 1;
                        $(btnSelf).removeClass('btnlook3').addClass('btnlook2');
                        $(btnSelf).parents('.item-lr').find('.fc-grey').attr('data-count', count);
                        $(btnSelf).parents('.item-lr').find('.fc-grey').html(count + '&ensp;条内容');
                        $(btnSelf).html('收藏');
                        _this.collectCount--;
                        if (_this.collectCount <= 0) {
                            _this.uncollectEvent();
                        }
                    }
                }
            }
            freshUserInfo(result,favoriteObj.batchCollect,fn_success);
        }
    },
    //收藏夹列表
    getList:function(){
        request_time++;
        if(request_time>3) return;

        var _this = this;
        var url = getFoldersUrl;
        $("#collectionList").empty();
        // url +="?access_token="+token+"&key="+_this.id+"&key_type="+_this.type;
        var data = {access_token:token,key:_this.id,key_type:_this.type};
        crossDomainAjax_post(url,onBack,data);

        function onBack(result) {
            var fn_success = function(result){
                request_time = 1;
                if(result.state=='success'){
                    var list =result.data;
                    var html = '';
                    if (list && list.length > 0) {
                        var count = 0;
                        for (var index in list) {
                            var item = list[index];
                            var btnStyle = 'btnlook2';
                            var btnTxt = '收藏';
                            if (item.collect == '1') {
                                btnStyle = 'btnlook3';
                                btnTxt = '已收藏';
                                count++;
                            }
                            html += '<li  class="item-lr" style="margin: 0;">'
                                + ' <div class="name">' + item.name + '</div>'
                                + ' <div class="fc-grey" data-count="' + item.count + '">' + item.count + '&ensp;条内容</div>'
                                + ' <div class="item-r" style="top:16px;right:2px"><a href="javascript:void(0)" class="cbtn-xs ' + btnStyle + '" data-id="' + item.fav_id + '">'+btnTxt+'</a></div>'
                                + '</li>';
                        }
                        $("#collectionList").html(html);
                        _this.collectCount = count;
                        $("#bg").show();
                        $("#collectionListBox").removeClass("hid");
                        document.documentElement.style.overflow = "hidden";
                    }
                }
            }
            freshUserInfo(result,favoriteObj.getList.bind(_this),fn_success);
        }
    },
    //绑定事件
    bindEvent:function(){
        var _this = this;
        $(document).on("click",_this.triggerBtn,function () {
            _this.getList();
        });

        /*收藏夹信息弹层 关闭/取消按钮*/
        $(document).on("click","#collectEdit .cancelDialog",function () {
            $("#collectEdit").addClass("hid");
            if($('#collectEdit h4.title').html()=='新建收藏夹'){
                $("#collectionListBox").removeClass('hid');
            }else{
                $("#bg").hide();
            }
        });
        /*弹出创建收藏夹*/
        $(document).on("click","#createBtn",function () {
            $("#collectionListBox").addClass("hid");
            $("#collectEdit > h4.title").html('新建收藏夹');
            $("#collectEdit").removeClass("hid");
            _this.clearCellectionInfo();
        });

        /*收藏夹信息弹层 确定按钮*/
        $(document).on("click","#saveCollection",function () {
            _this.saveCollectionInfo();
        });

        /*弹层中单选按钮public private*/
        $('input[name=favType]').change(function() {
            var value = $('input[name="favType"]:checked').val();
            if(value=='1'){
                $("#publicIcon").addClass("check");
                $("#privateIcon").removeClass("check");
            }else{
                $("#publicIcon").removeClass("check");
                $("#privateIcon").addClass("check");
            }
        });

        /*输入框监听输入*/
        $('#favName').bind('input propertychange', function() {
            $(this).val($(this).val().trim());
            var length = $(this).val().length;
            if(length>=20){
                var str = $(this).val().substring(0, 20);
                $(this).val(str)
            }else if(length<=0){
                $("#saveCollection").addClass("btnDisable");
            }else{
                $("#saveCollection").removeClass("btnDisable");
            }
            $(this).next().html(20-length);
        });

        /*点击收藏*/
        $("#collectionList").on("click",".cbtn-xs",function(){
            if($(this).hasClass('btnlook3')){
                _this.batchCollect('delete',this);
            }else{
                _this.batchCollect('add',this);
            }
        });
    }
};